package com.peng.rpc.socket.util;

import com.peng.rpc.entity.RpcRequest;
import com.peng.rpc.enumeration.PackageType;
import com.peng.rpc.serializer.CommonSerializer;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @author Wonderson
 * @email wpp.ds@foxmail.com
 * @date 2022-03-03 20:38
 */
public class ObjectWriter {

    private static final int MAGIC_NUMBER = 0xCAFEBABE;

    public static void writeObject(OutputStream os, Object obj, CommonSerializer serializer) throws IOException {
        os.write(intToBytes(MAGIC_NUMBER));
        int packageVersion = obj instanceof RpcRequest ? PackageType.REQUEST_PACKAGE.getCode() : PackageType.RESPONSE_PACKAGE.getCode();
        os.write(intToBytes(packageVersion));
        os.write(intToBytes(serializer.getCode()));
        byte[] bytes = serializer.serialize(obj);
        os.write(intToBytes(bytes.length));
        os.write(bytes);
        os.flush();
    }

    private static byte[] intToBytes(int value) {
        byte[] src = new byte[4];
        src[0] = (byte) ((value >> 24) & 0xFF);
        src[1] = (byte) ((value >> 16) & 0xFF);
        src[2] = (byte) ((value >> 8) & 0xFF);
        src[3] = (byte) (value & 0xFF);
        return src;
    }

}
